import { useRef, useCallback, useEffect } from 'react';

/**
 * 节流
 * @param {*} callback 节流函数
 * @param {*} wait 频率时常
 * @returns function
 */
export default function useThrottle(callback, wait) {
  const lastCallRef = useRef(0);
  const throttleFunc = useCallback((...args) => {
    const now = new Date();
    if (now - lastCallRef.current >= wait) {
      callback(...args);
      lastCallRef.current = now;
    }
  }, callback, wait);

  useEffect(() => {
    return () => {
      if (lastCallRef.current !== 0) {
        lastCallRef.current = null;
      }
    };
  }, []);
  return throttleFunc;
}
